package com.example.xd.Contorller;

import com.example.xd.DAO.userMapper;
import com.example.xd.Entity.Video;
import com.example.xd.Util.jwtUtil;
import com.example.xd.Service.VideoUploadService;
import com.example.xd.Util.VideoDurationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;


@RestController
@RequestMapping("/video")
public class videoController {


    private final jwtUtil jwtUtil;
    private final userMapper userMapper;
    private final VideoUploadService videoUploadService;
    private final VideoDurationUtil videoDurationUtil;

    @Autowired
    public videoController(jwtUtil jwtUtil,userMapper userMapper,VideoUploadService videoUploadService,VideoDurationUtil videoDurationUtil) {

this.jwtUtil=jwtUtil;
this.userMapper=userMapper;
this.videoUploadService=videoUploadService;
this.videoDurationUtil=videoDurationUtil;
    }

    //视频上传
    @PostMapping("/uploadVideo")
    public ResponseEntity<String> uploadVideo(@RequestHeader("Authorization") String authorizationHeader,
                                              @RequestParam("videoByte") MultipartFile videoByte,
                                              @RequestParam("videoImage") MultipartFile videoImage,
                                              Video video) throws IOException {
        // 验证授权信息是否合法并获取用户相关信息
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7);

            if (jwtUtil.validateToken(token)) {
                String email = jwtUtil.getUserEmailFromToken(token);
                int userId = userMapper.selectUserID(email);
                video.setUserId(userId);

                try {
                    // 获取视频字节数据和原始文件名
                    byte[] videoData = videoByte.getBytes();
                    String OriginalFilename = videoByte.getOriginalFilename();
//                    获取文件后缀名
                    String FileExtension = OriginalFilename.substring(OriginalFilename.lastIndexOf("."));

                    //获取用户输入的文件名
                    String GetVideoName = video.getName();

//添加加视频文件重名判定
                    if (videoUploadService.getVideoNameCount(GetVideoName + FileExtension) == true) {

                        //将后缀和文件名连接
                        String videoName = GetVideoName + FileExtension;
//定义系统时间，写入图片名称不会冲突
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

                        String VideoFileExtension = videoImage.getOriginalFilename().substring(videoImage.getOriginalFilename().lastIndexOf("."));
                        String videoImageName = simpleDateFormat + VideoFileExtension;

                        // 设置视频相关属性
                        video.setName(videoName);
                        video.setVideoUrl(video.getPath() + File.separator + videoName);


                        // 上传视频文件
                        videoUploadService.uploadVideo(videoData, videoName);

                        // 上传视频图片文件，优化异常处理逻辑
                        videoUploadService.uploadVideoImage(videoImage, videoImageName);

                        // 获取视频时长
                        double videoTime = videoDurationUtil.getVideoDuration(video.getPath() + File.separator + videoName);
                        System.out.println(videoTime);
                        video.setDuration((int) videoTime);

                        video.setThumbUrl(videoUploadService.videoImage_PATH + File.separator + videoImageName);

                        // 将视频信息插入数据库
                        userMapper.InsertVideo(video);

                        // 文件上传成功
                        return ResponseEntity.ok("文件上传开始");

                    } else {
                        return ResponseEntity.ok("视频名重复");
                    }


                } catch (IOException e) {
                    // 记录详细的异常信息
                    System.err.println("处理视频文件过程中出现异常，详细信息：" + e.getMessage());
                    // 返回500状态码表示服务器内部错误
                    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("视频文件处理出现问题");
                }
            }
        }
        // 授权验证不通过
        return ResponseEntity.ofNullable("请登录后操作");
    }

    @PostMapping
    public ResponseEntity<String> getVideo(@RequestParam (value = "Authorization",required = false) String authorization){
       if (authorization != null && authorization.startsWith("Bearer ")) {
           String token = authorization.substring(7);
           if (jwtUtil.validateToken(token)) {
               String email = jwtUtil.getUserEmailFromToken(token);
           }
       }
    }
}
